<?php
/**
 * 病历管理
 * 州弟医院信息系统 - 州弟学安全
 */

// 包含函数文件
require_once '../includes/functions.php';

// 检查用户是否已登录并具有管理员权限
if (!isLoggedIn() || !hasRole('admin')) {
    $_SESSION['error_msg'] = '您无权访问该页面';
    redirect('../login.php');
}

// 处理病历操作
$success = '';
$error = '';

// 处理删除病历请求
if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    $record_id = (int)$_GET['delete'];
    
    // 删除病历
    $sql = "DELETE FROM medical_records WHERE id = $record_id";
    
    if ($conn->query($sql)) {
        // 记录操作日志
        logAction($_SESSION['user_id'], '删除病历（ID：' . $record_id . '）');
        
        $success = '病历删除成功！';
    } else {
        $error = '删除病历失败：' . $conn->error;
    }
}

// 处理添加/编辑病历表单提交
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['add_record']) || isset($_POST['edit_record'])) {
        $patient_id = isset($_POST['patient_id']) ? (int)$_POST['patient_id'] : 0;
        $doctor_id = isset($_POST['doctor_id']) ? (int)$_POST['doctor_id'] : 0;
        $record_date = $_POST['record_date'] ?? date('Y-m-d');
        $diagnosis = $_POST['diagnosis'] ?? '';
        $symptoms = $_POST['symptoms'] ?? '';
        $treatment = $_POST['treatment'] ?? '';
        $notes = $_POST['notes'] ?? '';
        $record_id = isset($_POST['record_id']) ? (int)$_POST['record_id'] : 0;
        
        // 基本验证
        if (empty($patient_id) || empty($doctor_id) || empty($diagnosis)) {
            $error = '请填写所有必填字段';
        } else {
            // 处理表单数据
            $patient_id = $conn->real_escape_string($patient_id);
            $doctor_id = $conn->real_escape_string($doctor_id);
            $record_date = $conn->real_escape_string($record_date);
            $diagnosis = $conn->real_escape_string($diagnosis);
            $symptoms = $conn->real_escape_string($symptoms);
            $treatment = $conn->real_escape_string($treatment);
            $notes = $conn->real_escape_string($notes);
            
            // 添加新病历
            if (isset($_POST['add_record'])) {
                $sql = "INSERT INTO medical_records (patient_id, doctor_id, record_date, diagnosis, symptoms, treatment, notes, created_at) 
                        VALUES ('$patient_id', '$doctor_id', '$record_date', '$diagnosis', '$symptoms', '$treatment', '$notes', NOW())";
                
                if ($conn->query($sql)) {
                    $new_record_id = $conn->insert_id;
                    
                    // 记录操作日志
                    logAction($_SESSION['user_id'], '添加病历（ID：' . $new_record_id . '）');
                    
                    $success = '病历添加成功！';
                } else {
                    $error = '添加病历失败：' . $conn->error;
                }
            }
            // 编辑现有病历
            else {
                $sql = "UPDATE medical_records SET patient_id = '$patient_id', doctor_id = '$doctor_id', 
                        record_date = '$record_date', diagnosis = '$diagnosis', symptoms = '$symptoms', 
                        treatment = '$treatment', notes = '$notes', updated_at = NOW() 
                        WHERE id = $record_id";
                
                if ($conn->query($sql)) {
                    // 记录操作日志
                    logAction($_SESSION['user_id'], '更新病历（ID：' . $record_id . '）');
                    
                    $success = '病历更新成功！';
                } else {
                    $error = '更新病历失败：' . $conn->error;
                }
            }
        }
    }
}

// 获取所有病历
$records = [];
$sql = "SELECT mr.*, p.name as patient_name, d.name as doctor_name 
        FROM medical_records mr 
        LEFT JOIN patients p ON mr.patient_id = p.id 
        LEFT JOIN doctors d ON mr.doctor_id = d.id 
        ORDER BY mr.record_date DESC";
$result = $conn->query($sql);
if ($result && $result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $records[] = $row;
    }
}

// 如果是编辑请求，获取病历信息
$edit_record = null;
if (isset($_GET['edit']) && is_numeric($_GET['edit'])) {
    $record_id = (int)$_GET['edit'];
    $sql = "SELECT * FROM medical_records WHERE id = $record_id";
    $result = $conn->query($sql);
    
    if ($result && $result->num_rows > 0) {
        $edit_record = $result->fetch_assoc();
    }
}

// 获取所有患者和医生（用于下拉选择）
$patients = [];
$sql = "SELECT id, name FROM patients ORDER BY name";
$result = $conn->query($sql);
if ($result && $result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $patients[] = $row;
    }
}

$doctors = [];
$sql = "SELECT id, name FROM doctors ORDER BY name";
$result = $conn->query($sql);
if ($result && $result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $doctors[] = $row;
    }
}

?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>病历管理 - <?php echo SITE_NAME; ?></title>
    <link rel="stylesheet" href="/assets\css/bootstrap_69c9e605.min.css">
    <link rel="stylesheet" href="/assets\css/all_3b858821.min.css">
    <link rel="stylesheet" href="/assets\css/style.css">
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- 侧边栏 -->
            <div class="col-md-2 px-0 admin-sidebar">
                <div class="py-3 px-3 bg-dark">
                    <a href="<?php echo SITE_URL; ?>admin/" class="text-white text-decoration-none">
                        <i class="fas fa-hospital-alt mr-2"></i>管理后台
                    </a>
                </div>
                <div class="p-3">
                    <div class="text-white mb-3">
                        <i class="fas fa-user-circle mr-1"></i> <?php echo $_SESSION['username']; ?>
                    </div>
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>admin/">
                                <i class="fas fa-tachometer-alt mr-2"></i>仪表盘
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>admin/users.php">
                                <i class="fas fa-users mr-2"></i>用户管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>admin/patients.php">
                                <i class="fas fa-user-injured mr-2"></i>患者管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>admin/doctors.php">
                                <i class="fas fa-user-md mr-2"></i>医生管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>admin/departments.php">
                                <i class="fas fa-hospital mr-2"></i>科室管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>admin/appointments.php">
                                <i class="fas fa-calendar-check mr-2"></i>预约管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>admin/medicines.php">
                                <i class="fas fa-pills mr-2"></i>药品管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link active" href="<?php echo SITE_URL; ?>admin/records.php">
                                <i class="fas fa-notes-medical mr-2"></i>病历管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>admin/logs.php">
                                <i class="fas fa-history mr-2"></i>系统日志
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>admin/settings.php">
                                <i class="fas fa-cog mr-2"></i>系统设置
                            </a>
                        </li>
                        <li class="nav-item mt-3">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>">
                                <i class="fas fa-home mr-2"></i>返回前台
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>logout.php">
                                <i class="fas fa-sign-out-alt mr-2"></i>退出登录
                            </a>
                        </li>
                    </ul>
                </div>
            </div>
            
            <!-- 主内容区 -->
            <div class="col-md-10 ml-sm-auto px-4 py-3">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">病历管理</h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <button type="button" class="btn btn-sm btn-primary" data-toggle="modal" data-target="#addRecordModal">
                            <i class="fas fa-plus mr-1"></i> 添加病历
                        </button>
                    </div>
                </div>
                
                <?php if ($success): ?>
                    <div class="alert alert-success">
                        <?php echo $success; ?>
                    </div>
                <?php endif; ?>
                
                <?php if ($error): ?>
                    <div class="alert alert-danger">
                        <?php echo $error; ?>
                    </div>
                <?php endif; ?>
                
                <!-- 病历列表 -->
                <div class="card">
                    <div class="card-header">
                        <div class="row align-items-center">
                            <div class="col">
                                <h5 class="mb-0">病历列表</h5>
                            </div>
                            <div class="col-auto">
                                <div class="input-group">
                                    <input type="text" class="form-control form-control-sm" id="searchInput" placeholder="搜索病历...">
                                    <div class="input-group-append">
                                        <button class="btn btn-sm btn-outline-secondary" type="button">
                                            <i class="fas fa-search"></i>
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table table-hover table-striped" id="recordTable">
                                <thead>
                                    <tr>
                                        <th onclick="sortTable(0)">ID <i class="fas fa-sort text-muted ml-1"></i></th>
                                        <th onclick="sortTable(1)">患者姓名 <i class="fas fa-sort text-muted ml-1"></i></th>
                                        <th onclick="sortTable(2)">医生姓名 <i class="fas fa-sort text-muted ml-1"></i></th>
                                        <th onclick="sortTable(3)">诊断日期 <i class="fas fa-sort text-muted ml-1"></i></th>
                                        <th onclick="sortTable(4)">诊断结果 <i class="fas fa-sort text-muted ml-1"></i></th>
                                        <th onclick="sortTable(5)">创建时间 <i class="fas fa-sort text-muted ml-1"></i></th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if (empty($records)): ?>
                                        <tr>
                                            <td colspan="7" class="text-center">暂无病历记录</td>
                                        </tr>
                                    <?php else: ?>
                                        <?php foreach ($records as $record): ?>
                                            <tr>
                                                <td><?php echo $record['id']; ?></td>
                                                <td><?php echo $record['patient_name']; ?></td>
                                                <td><?php echo $record['doctor_name']; ?></td>
                                                <td><?php echo date('Y-m-d', strtotime($record['record_date'])); ?></td>
                                                <td><?php echo mb_substr($record['diagnosis'], 0, 30) . (mb_strlen($record['diagnosis']) > 30 ? '...' : ''); ?></td>
                                                <td><?php echo date('Y-m-d H:i', strtotime($record['created_at'])); ?></td>
                                                <td>
                                                    <button type="button" class="btn btn-sm btn-info view-btn" data-id="<?php echo $record['id']; ?>" title="查看详情">
                                                        <i class="fas fa-eye"></i>
                                                    </button>
                                                    <a href="?edit=<?php echo $record['id']; ?>" class="btn btn-sm btn-warning" title="编辑病历">
                                                        <i class="fas fa-edit"></i>
                                                    </a>
                                                    <a href="?delete=<?php echo $record['id']; ?>" class="btn btn-sm btn-danger" title="删除病历" onclick="return confirm('确定要删除此病历记录吗？此操作不可恢复！');">
                                                        <i class="fas fa-trash-alt"></i>
                                                    </a>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                    <div class="card-footer">
                        <div class="row align-items-center">
                            <div class="col">
                                <small class="text-muted">共 <?php echo count($records); ?> 条病历记录</small>
                            </div>
                            <div class="col-auto">
                                <div class="btn-group">
                                    <button type="button" class="btn btn-sm btn-outline-secondary" id="exportBtn">
                                        <i class="fas fa-file-export mr-1"></i> 导出数据
                                    </button>
                                    <button type="button" class="btn btn-sm btn-outline-secondary dropdown-toggle" data-toggle="dropdown">
                                        <i class="fas fa-filter mr-1"></i> 归档选项
                                    </button>
                                    <div class="dropdown-menu dropdown-menu-right">
                                        <a class="dropdown-item" href="#" data-archive="all">查看全部</a>
                                        <a class="dropdown-item" href="#" data-archive="active">活跃病历</a>
                                        <a class="dropdown-item" href="#" data-archive="archived">已归档病历</a>
                                        <div class="dropdown-divider"></div>
                                        <a class="dropdown-item text-primary" href="#" data-toggle="modal" data-target="#archiveSettingsModal">
                                            <i class="fas fa-cog mr-1"></i> 归档设置
                                        </a>
                                    </div>
                                </div>
                            </div>
                            <div class="col-auto ml-2">
                                <nav aria-label="Page navigation">
                                    <ul class="pagination pagination-sm mb-0">
                                        <li class="page-item disabled"><a class="page-link" href="#">上一页</a></li>
                                        <li class="page-item active"><a class="page-link" href="#">1</a></li>
                                        <li class="page-item"><a class="page-link" href="#">2</a></li>
                                        <li class="page-item"><a class="page-link" href="#">3</a></li>
                                        <li class="page-item"><a class="page-link" href="#">下一页</a></li>
                                    </ul>
                                </nav>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 高级分析卡片 -->
                <div class="card mt-4">
                    <div class="card-header">
                        <h5 class="mb-0">病历数据分析</h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6">
                                <canvas id="recordsChart" height="200"></canvas>
                            </div>
                            <div class="col-md-6">
                                <h6 class="border-bottom pb-2 mb-3">最常见诊断</h6>
                                <div class="table-responsive">
                                    <table class="table table-sm">
                                        <thead>
                                            <tr>
                                                <th>诊断名称</th>
                                                <th>病例数</th>
                                                <th>占比</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <tr>
                                                <td>高血压</td>
                                                <td>24</td>
                                                <td>18%</td>
                                            </tr>
                                            <tr>
                                                <td>糖尿病</td>
                                                <td>19</td>
                                                <td>14%</td>
                                            </tr>
                                            <tr>
                                                <td>上呼吸道感染</td>
                                                <td>15</td>
                                                <td>11%</td>
                                            </tr>
                                            <tr>
                                                <td>骨关节炎</td>
                                                <td>12</td>
                                                <td>9%</td>
                                            </tr>
                                            <tr>
                                                <td>胃炎</td>
                                                <td>10</td>
                                                <td>7%</td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 版权信息 -->
                <footer class="mt-5 text-center text-muted">
                    <p>
                        &copy; <?php echo date('Y'); ?> <?php echo SITE_NAME; ?>. 版权所有
                        <br>
                        <small>Powered by <a href="#" class="text-muted">州弟学安全</a> | 版本 <?php echo VERSION; ?></small>
                    </p>
                </footer>
            </div>
        </div>
    </div>
    
    <!-- 添加病历模态框 -->
    <div class="modal fade" id="addRecordModal" tabindex="-1" role="dialog" aria-labelledby="addRecordModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addRecordModalLabel">添加病历</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <form method="post">
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="patient_id">患者 <span class="text-danger">*</span></label>
                                    <select class="form-control" id="patient_id" name="patient_id" required>
                                        <option value="">请选择患者</option>
                                        <?php foreach ($patients as $patient): ?>
                                            <option value="<?php echo $patient['id']; ?>"><?php echo $patient['name']; ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="doctor_id">医生 <span class="text-danger">*</span></label>
                                    <select class="form-control" id="doctor_id" name="doctor_id" required>
                                        <option value="">请选择医生</option>
                                        <?php foreach ($doctors as $doctor): ?>
                                            <option value="<?php echo $doctor['id']; ?>"><?php echo $doctor['name']; ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="record_date">诊断日期 <span class="text-danger">*</span></label>
                            <input type="date" class="form-control" id="record_date" name="record_date" value="<?php echo date('Y-m-d'); ?>" required>
                        </div>
                        <div class="form-group">
                            <label for="symptoms">症状描述</label>
                            <textarea class="form-control" id="symptoms" name="symptoms" rows="3"></textarea>
                        </div>
                        <div class="form-group">
                            <label for="diagnosis">诊断结果 <span class="text-danger">*</span></label>
                            <textarea class="form-control" id="diagnosis" name="diagnosis" rows="3" required></textarea>
                        </div>
                        <div class="form-group">
                            <label for="treatment">治疗方案</label>
                            <textarea class="form-control" id="treatment" name="treatment" rows="3"></textarea>
                        </div>
                        <div class="form-group">
                            <label for="notes">备注</label>
                            <textarea class="form-control" id="notes" name="notes" rows="2"></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                        <button type="submit" name="add_record" class="btn btn-primary">添加</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <!-- 编辑病历模态框 -->
    <?php if ($edit_record): ?>
    <div class="modal fade" id="editRecordModal" tabindex="-1" role="dialog" aria-labelledby="editRecordModalLabel" aria-hidden="true" data-show="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editRecordModalLabel">编辑病历</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <form method="post">
                    <div class="modal-body">
                        <input type="hidden" name="record_id" value="<?php echo $edit_record['id']; ?>">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="edit_patient_id">患者 <span class="text-danger">*</span></label>
                                    <select class="form-control" id="edit_patient_id" name="patient_id" required>
                                        <option value="">请选择患者</option>
                                        <?php foreach ($patients as $patient): ?>
                                            <option value="<?php echo $patient['id']; ?>" <?php echo $edit_record['patient_id'] == $patient['id'] ? 'selected' : ''; ?>>
                                                <?php echo $patient['name']; ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="edit_doctor_id">医生 <span class="text-danger">*</span></label>
                                    <select class="form-control" id="edit_doctor_id" name="doctor_id" required>
                                        <option value="">请选择医生</option>
                                        <?php foreach ($doctors as $doctor): ?>
                                            <option value="<?php echo $doctor['id']; ?>" <?php echo $edit_record['doctor_id'] == $doctor['id'] ? 'selected' : ''; ?>>
                                                <?php echo $doctor['name']; ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="edit_record_date">诊断日期 <span class="text-danger">*</span></label>
                            <input type="date" class="form-control" id="edit_record_date" name="record_date" value="<?php echo date('Y-m-d', strtotime($edit_record['record_date'])); ?>" required>
                        </div>
                        <div class="form-group">
                            <label for="edit_symptoms">症状描述</label>
                            <textarea class="form-control" id="edit_symptoms" name="symptoms" rows="3"><?php echo $edit_record['symptoms']; ?></textarea>
                        </div>
                        <div class="form-group">
                            <label for="edit_diagnosis">诊断结果 <span class="text-danger">*</span></label>
                            <textarea class="form-control" id="edit_diagnosis" name="diagnosis" rows="3" required><?php echo $edit_record['diagnosis']; ?></textarea>
                        </div>
                        <div class="form-group">
                            <label for="edit_treatment">治疗方案</label>
                            <textarea class="form-control" id="edit_treatment" name="treatment" rows="3"><?php echo $edit_record['treatment']; ?></textarea>
                        </div>
                        <div class="form-group">
                            <label for="edit_notes">备注</label>
                            <textarea class="form-control" id="edit_notes" name="notes" rows="2"><?php echo $edit_record['notes']; ?></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                        <button type="submit" name="edit_record" class="btn btn-primary">保存</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <script>
        $(document).ready(function() {
            $('#editRecordModal').modal('show');
        });
    </script>
    <?php endif; ?>
    
    <!-- 病历详情模态框 -->
    <div class="modal fade" id="viewRecordModal" tabindex="-1" role="dialog" aria-labelledby="viewRecordModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="viewRecordModalLabel">病历详情</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body" id="viewRecordBody">
                    <div class="text-center">
                        <div class="spinner-border text-primary" role="status">
                            <span class="sr-only">加载中...</span>
                        </div>
                        <p class="mt-2">加载病历信息...</p>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                    <div class="btn-group">
                        <button type="button" class="btn btn-primary" id="printRecord">
                            <i class="fas fa-print mr-1"></i> 打印病历
                        </button>
                        <button type="button" class="btn btn-primary dropdown-toggle dropdown-toggle-split" data-toggle="dropdown">
                            <span class="sr-only">导出选项</span>
                        </button>
                        <div class="dropdown-menu dropdown-menu-right">
                            <a class="dropdown-item" href="#" id="exportPDF">
                                <i class="fas fa-file-pdf mr-1"></i> 导出为PDF
                            </a>
                            <a class="dropdown-item" href="#" id="exportWord">
                                <i class="fas fa-file-word mr-1"></i> 导出为Word
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 归档设置模态框 -->
    <div class="modal fade" id="archiveSettingsModal" tabindex="-1" role="dialog" aria-labelledby="archiveSettingsModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="archiveSettingsModalLabel">病历归档设置</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label for="autoArchiveDays">自动归档天数</label>
                        <div class="input-group">
                            <input type="number" class="form-control" id="autoArchiveDays" value="90" min="30">
                            <div class="input-group-append">
                                <span class="input-group-text">天</span>
                            </div>
                        </div>
                        <small class="form-text text-muted">超过此天数的病历将自动归档</small>
                    </div>
                    <div class="form-group">
                        <label>归档选项</label>
                        <div class="custom-control custom-switch">
                            <input type="checkbox" class="custom-control-input" id="archiveNotify" checked>
                            <label class="custom-control-label" for="archiveNotify">归档时通知相关医生</label>
                        </div>
                        <div class="custom-control custom-switch mt-2">
                            <input type="checkbox" class="custom-control-input" id="archiveReadOnly" checked>
                            <label class="custom-control-label" for="archiveReadOnly">归档后设为只读</label>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="archiveCategories">归档类别</label>
                        <select class="form-control" id="archiveCategories" multiple>
                            <option selected>一般病历</option>
                            <option selected>住院病历</option>
                            <option selected>手术病历</option>
                            <option selected>检查报告</option>
                            <option>其他</option>
                        </select>
                        <small class="form-text text-muted">选择需要自动归档的病历类别</small>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="saveArchiveSettings">保存设置</button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 上传检查报告模态框 -->
    <div class="modal fade" id="uploadReportModal" tabindex="-1" role="dialog" aria-labelledby="uploadReportModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="uploadReportModalLabel">上传检查报告</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="reportUploadForm">
                        <input type="hidden" id="report_record_id" name="record_id">
                        <div class="form-group">
                            <label for="reportType">报告类型</label>
                            <select class="form-control" id="reportType" name="report_type" required>
                                <option value="">选择报告类型</option>
                                <option value="blood">血液检查</option>
                                <option value="imaging">影像检查</option>
                                <option value="pathology">病理检查</option>
                                <option value="ecg">心电图</option>
                                <option value="other">其他检查</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="reportDate">检查日期</label>
                            <input type="date" class="form-control" id="reportDate" name="report_date" value="<?php echo date('Y-m-d'); ?>" required>
                        </div>
                        <div class="form-group">
                            <label for="reportFile">报告文件</label>
                            <div class="custom-file">
                                <input type="file" class="custom-file-input" id="reportFile" name="report_file" required>
                                <label class="custom-file-label" for="reportFile">选择文件</label>
                            </div>
                            <small class="form-text text-muted">支持 PDF, JPG, PNG 文件，最大 5MB</small>
                        </div>
                        <div class="form-group">
                            <label for="reportDescription">检查说明</label>
                            <textarea class="form-control" id="reportDescription" name="report_description" rows="3"></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="submitReport">上传报告</button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 关联药品模态框 -->
    <div class="modal fade" id="linkMedicineModal" tabindex="-1" role="dialog" aria-labelledby="linkMedicineModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="linkMedicineModalLabel">关联药品处方</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <input type="hidden" id="prescription_record_id">
                    <div class="row mb-3">
                        <div class="col">
                            <div class="input-group">
                                <input type="text" class="form-control" id="medicineSearch" placeholder="搜索药品...">
                                <div class="input-group-append">
                                    <button class="btn btn-outline-secondary" type="button">
                                        <i class="fas fa-search"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="card">
                                <div class="card-header bg-light py-2">
                                    <h6 class="mb-0">可选药品</h6>
                                </div>
                                <div class="card-body p-0" style="height: 300px; overflow-y: auto;">
                                    <div class="list-group list-group-flush" id="availableMedicines">
                                        <!-- 药品列表将通过AJAX加载 -->
                                        <div class="text-center py-3">
                                            <div class="spinner-border spinner-border-sm text-primary" role="status">
                                                <span class="sr-only">加载中...</span>
                                            </div>
                                            <p class="mt-2 text-muted">加载药品列表...</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="card">
                                <div class="card-header bg-light py-2">
                                    <h6 class="mb-0">已选药品</h6>
                                </div>
                                <div class="card-body p-0" style="height: 300px; overflow-y: auto;">
                                    <div class="list-group list-group-flush" id="selectedMedicines">
                                        <div class="list-group-item text-center text-muted py-5">
                                            <i class="fas fa-pills fa-2x mb-2"></i>
                                            <p>尚未选择药品</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="form-group mt-3">
                        <label for="prescriptionNotes">处方说明</label>
                        <textarea class="form-control" id="prescriptionNotes" rows="2" placeholder="用法用量等说明信息..."></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="savePrescription">保存处方</button>
                </div>
            </div>
        </div>
    </div>

    <script src="/assets\js/jquery-3_7b53a2dc.5.1.min.js"></script></script></script></script>
    <script src="/assets\js/popper_9c21e708.min.js"></script></script></script></script>
    <script src="/assets\js/bootstrap_a618e9ff.min.js"></script></script></script></script>
    <script src="/assets\js/Chart_9b2a28ab.min.js"></script></script></script></script>
    <script src="/assets\js/html2pdf_3719da26.bundle.min.js"></script></script></script></script>
    <script src="/assets\js/main.js"></script></script>
    <script>
        // 排序表格
        function sortTable(n) {
            var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
            table = document.getElementById("recordTable");
            switching = true;
            dir = "asc";
            
            while (switching) {
                switching = false;
                rows = table.rows;
                
                for (i = 1; i < (rows.length - 1); i++) {
                    shouldSwitch = false;
                    x = rows[i].getElementsByTagName("TD")[n];
                    y = rows[i + 1].getElementsByTagName("TD")[n];
                    
                    if (dir == "asc") {
                        if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
                            shouldSwitch = true;
                            break;
                        }
                    } else if (dir == "desc") {
                        if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
                            shouldSwitch = true;
                            break;
                        }
                    }
                }
                
                if (shouldSwitch) {
                    rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
                    switching = true;
                    switchcount++;
                } else {
                    if (switchcount == 0 && dir == "asc") {
                        dir = "desc";
                        switching = true;
                    }
                }
            }
        }
        
        // 表格搜索功能
        $(document).ready(function(){
            $("#searchInput").on("keyup", function() {
                var value = $(this).val().toLowerCase();
                $("#recordTable tbody tr").filter(function() {
                    $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
                });
            });
            
            // 查看病历详情
            $(".view-btn").click(function() {
                var recordId = $(this).data('id');
                $("#viewRecordModal").modal('show');
                
                // 在实际应用中，这里会通过AJAX加载病历的详细信息
                // 这里仅作为示例，模拟加载效果
                setTimeout(function() {
                    // 假设这里是从服务器返回的数据
                    var record = <?php echo json_encode($records[0] ?? []); ?>;
                    
                    if (record) {
                        var html = '<div class="record-header mb-4">' +
                                   '<h4 class="text-center">病历记录</h4>' +
                                   '<div class="row">' +
                                   '<div class="col-md-6"><p><strong>患者姓名：</strong> ' + record.patient_name + '</p></div>' +
                                   '<div class="col-md-6"><p><strong>主治医师：</strong> ' + record.doctor_name + '</p></div>' +
                                   '<div class="col-md-6"><p><strong>诊断日期：</strong> ' + record.record_date + '</p></div>' +
                                   '<div class="col-md-6"><p><strong>病历编号：</strong> ' + record.id + '</p></div>' +
                                   '</div>' +
                                   '<hr></div>' +
                                   '<div class="record-body">' +
                                   '<div class="form-group">' +
                                   '<label><strong>症状描述：</strong></label>' +
                                   '<p>' + (record.symptoms || '无') + '</p>' +
                                   '</div>' +
                                   '<div class="form-group">' +
                                   '<label><strong>诊断结果：</strong></label>' +
                                   '<p>' + record.diagnosis + '</p>' +
                                   '</div>' +
                                   '<div class="form-group">' +
                                   '<label><strong>治疗方案：</strong></label>' +
                                   '<p>' + (record.treatment || '无') + '</p>' +
                                   '</div>' +
                                   '<div class="form-group">' +
                                   '<label><strong>备注：</strong></label>' +
                                   '<p>' + (record.notes || '无') + '</p>' +
                                   '</div>' +
                                   '</div>';
                        
                        $("#viewRecordBody").html(html);
                    } else {
                        $("#viewRecordBody").html('<div class="alert alert-danger">加载病历信息失败</div>');
                    }
                }, 1000);
            });
            
            // 打印病历功能
            $("#printRecord").click(function() {
                var printContents = $("#viewRecordBody").html();
                var originalContents = document.body.innerHTML;
                
                document.body.innerHTML = '<div class="container mt-4">' + printContents + '</div>';
                window.print();
                document.body.innerHTML = originalContents;
                
                // 重新绑定事件（因为DOM被替换了）
                location.reload();
            });
            
            // 病历数据分析图表
            $(document).ready(function() {
                var ctx = document.getElementById('recordsChart').getContext('2d');
                var recordsChart = new Chart(ctx, {
                    type: 'line',
                    data: {
                        labels: ['1月', '2月', '3月', '4月', '5月', '6月'],
                        datasets: [{
                            label: '新增病历',
                            data: [12, 19, 15, 17, 22, 18],
                            backgroundColor: 'rgba(54, 162, 235, 0.2)',
                            borderColor: 'rgba(54, 162, 235, 1)',
                            borderWidth: 1
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        scales: {
                            yAxes: [{
                                ticks: {
                                    beginAtZero: true
                                }
                            }]
                        }
                    }
                });
                
                // 导出PDF功能
                $("#exportPDF").click(function(e) {
                    e.preventDefault();
                    
                    var element = document.getElementById('viewRecordBody');
                    var opt = {
                        margin: 1,
                        filename: '病历记录.pdf',
                        image: { type: 'jpeg', quality: 0.98 },
                        html2canvas: { scale: 2 },
                        jsPDF: { unit: 'cm', format: 'a4', orientation: 'portrait' }
                    };
                    
                    // 生成PDF
                    html2pdf().set(opt).from(element).save();
                });
                
                // 数据导出功能
                $("#exportBtn").click(function() {
                    // 这里应该实现导出功能，例如CSV、Excel等
                    alert("导出功能将在此实现");
                });
                
                // 病历归档功能
                $("[data-archive]").click(function(e) {
                    e.preventDefault();
                    var type = $(this).data("archive");
                    
                    // 这里应该实现根据归档状态筛选病历的功能
                    alert("已切换到" + (type === "all" ? "全部病历" : (type === "active" ? "活跃病历" : "已归档病历")));
                });
                
                // 保存归档设置
                $("#saveArchiveSettings").click(function() {
                    var days = $("#autoArchiveDays").val();
                    var notify = $("#archiveNotify").is(":checked");
                    var readOnly = $("#archiveReadOnly").is(":checked");
                    
                    // 这里应该实现保存设置的功能
                    alert("归档设置已保存");
                    $("#archiveSettingsModal").modal("hide");
                });
                
                // 上传检查报告
                $("#submitReport").click(function() {
                    // 这里应该实现报告上传功能
                    alert("报告上传功能将在此实现");
                    $("#uploadReportModal").modal("hide");
                });
                
                // 自定义文件输入框显示文件名
                $(".custom-file-input").on("change", function() {
                    var fileName = $(this).val().split("\\").pop();
                    $(this).siblings(".custom-file-label").addClass("selected").html(fileName);
                });
                
                // 增加病历详情模态框功能按钮
                $(".view-btn").click(function() {
                    var recordId = $(this).data('id');
                    
                    // 添加上传报告和关联药品按钮
                    setTimeout(function() {
                        var btnGroup = `
                        <div class="btn-group mt-3">
                            <button type="button" class="btn btn-outline-secondary" onclick="openUploadModal(${recordId})">
                                <i class="fas fa-upload mr-1"></i> 上传检查报告
                            </button>
                            <button type="button" class="btn btn-outline-secondary" onclick="openMedicineModal(${recordId})">
                                <i class="fas fa-prescription-bottle-alt mr-1"></i> 关联药品
                            </button>
                        </div>`;
                        
                        $("#viewRecordBody .record-body").append(btnGroup);
                    }, 1000);
                });
            });
            
            // 打开上传报告模态框
            function openUploadModal(recordId) {
                $("#report_record_id").val(recordId);
                $("#viewRecordModal").modal("hide");
                $("#uploadReportModal").modal("show");
            }
            
            // 打开关联药品模态框
            function openMedicineModal(recordId) {
                $("#prescription_record_id").val(recordId);
                $("#viewRecordModal").modal("hide");
                $("#linkMedicineModal").modal("show");
                
                // 模拟加载药品列表
                setTimeout(function() {
                    var medicinesList = `
                        <a href="#" class="list-group-item list-group-item-action medicine-item" data-id="1">
                            <div class="d-flex w-100 justify-content-between">
                                <h6 class="mb-1">阿莫西林胶囊</h6>
                                <small>非处方药</small>
                            </div>
                            <p class="mb-1">规格：500mg*24粒</p>
                        </a>
                        <a href="#" class="list-group-item list-group-item-action medicine-item" data-id="2">
                            <div class="d-flex w-100 justify-content-between">
                                <h6 class="mb-1">布洛芬片</h6>
                                <small>非处方药</small>
                            </div>
                            <p class="mb-1">规格：0.2g*10片</p>
                        </a>
                        <a href="#" class="list-group-item list-group-item-action medicine-item" data-id="3">
                            <div class="d-flex w-100 justify-content-between">
                                <h6 class="mb-1">头孢克肟胶囊</h6>
                                <small>处方药</small>
                            </div>
                            <p class="mb-1">规格：100mg*6粒</p>
                        </a>
                        <a href="#" class="list-group-item list-group-item-action medicine-item" data-id="4">
                            <div class="d-flex w-100 justify-content-between">
                                <h6 class="mb-1">维生素C片</h6>
                                <small>保健品</small>
                            </div>
                            <p class="mb-1">规格：100mg*60片</p>
                        </a>
                        <a href="#" class="list-group-item list-group-item-action medicine-item" data-id="5">
                            <div class="d-flex w-100 justify-content-between">
                                <h6 class="mb-1">氯雷他定片</h6>
                                <small>处方药</small>
                            </div>
                            <p class="mb-1">规格：10mg*6片</p>
                        </a>`;
                    
                    $("#availableMedicines").html(medicinesList);
                    
                    // 点击添加药品
                    $(".medicine-item").click(function(e) {
                        e.preventDefault();
                        var id = $(this).data("id");
                        var name = $(this).find("h6").text();
                        var spec = $(this).find("p").text();
                        
                        // 检查是否已添加
                        if ($("#medicine-" + id).length === 0) {
                            var selectedMedicine = `
                                <div class="list-group-item" id="medicine-${id}">
                                    <div class="d-flex w-100 justify-content-between">
                                        <h6 class="mb-1">${name}</h6>
                                        <button type="button" class="close" onclick="removeMedicine(${id})">
                                            <span aria-hidden="true">&times;</span>
                                        </button>
                                    </div>
                                    <p class="mb-1">${spec}</p>
                                    <div class="input-group input-group-sm mt-2">
                                        <div class="input-group-prepend">
                                            <span class="input-group-text">用量</span>
                                        </div>
                                        <input type="text" class="form-control" placeholder="如：每日3次，每次1片">
                                    </div>
                                </div>`;
                            
                            // 移除空提示
                            if ($("#selectedMedicines .text-center").length > 0) {
                                $("#selectedMedicines").empty();
                            }
                            
                            $("#selectedMedicines").append(selectedMedicine);
                        }
                    });
                }, 500);
            }
            
            // 移除已选药品
            function removeMedicine(id) {
                $("#medicine-" + id).remove();
                
                // 如果没有药品，显示提示
                if ($("#selectedMedicines").children().length === 0) {
                    $("#selectedMedicines").html(`
                        <div class="list-group-item text-center text-muted py-5">
                            <i class="fas fa-pills fa-2x mb-2"></i>
                            <p>尚未选择药品</p>
                        </div>`);
                }
            }
        });
    </script>
</body>
</html> 